import React, { useState, useEffect } from 'react';
import {
  FileExcelOutlined, ProfileOutlined, ReloadOutlined, MinusSquareOutlined,
  PlusSquareOutlined, EditOutlined, UserOutlined, ApartmentOutlined, SearchOutlined, EllipsisOutlined
} from '@ant-design/icons';
import { Modal, Select, Button, Spin, Checkbox, DatePicker, Popconfirm, Tree, Input, Row, Col, Card, Form, Divider, Dropdown, Menu, Tabs } from 'antd';
import { createFromIconfontCN } from '@ant-design/icons';
import { useHistory } from 'react-router-dom';
import logo from '../../../img/julongSRM/chlogo.png'
import useStore from '../../useStore.js'
import { clearCache, useDidCache, useDidRecover, dropByCacheKey } from 'react-router-cache-route';

import {
  openNotification_util, fetchsync_util, useexcelauto,
  getCurrentDate_util,
  dealnullorundenfined,
  convertISODateTimeToYYYYMMDDHHMMSS
} from '../util/util.js'
import Custom_table_hooks_config from '../newmes/custom_table_hooks_config.js'

var storage = window.localStorage;
const { Option } = Select;
const { Search } = Input;

const IconFont = createFromIconfontCN({
  scriptUrl: 'http://111.77.154.58:2233/icon.js',
});

// 初始化表格列配置
const initColumns = [
  {
    title: '组织代码',
    dataIndex: 'bmbm',
    key: 'bmbm',
    width: 120,
    fixed: 'left',
    sorter: true,
    show: true
  },
  {
    title: '组织名称',
    dataIndex: 'bmmc',
    key: 'bmmc',
    width: 200,
    fixed: 'left',
    sorter: true,
    show: true
  },
  {
    title: '简称',
    dataIndex: 'short_name',
    key: 'short_name',
    width: 150,
    sorter: true,
    show: true
  },
  {
    title: '组织类型',
    dataIndex: 'org_type',
    key: 'org_type',
    width: 100,
    sorter: true,
    show: true
  },
  
  {
    title: '负责人',
    dataIndex: 'manager',
    key: 'manager',
    width: 120,
    sorter: true,
    show: true
  },
  {
    title: '创建日期',
    dataIndex: 'create_date',
    key: 'create_date',
    width: 120,
    sorter: true,
    show: true
  },
  {
    title: '备注',
    dataIndex: 'remark',
    key: 'remark',
    width: 200,
    sorter: true,
    show: true
  }
];

const TreeManage = () => {
  const history = useHistory();
  const [selectedRows, setSelectedRows] = useState([])
  const [selectedRowKeys, setSelectedRowKeys] = useState([])
  const [isLoading, setIsLoading] = useState(false)
  const [treeData, setTreeData] = useState([])
  const [tableData, setTableData] = useState([])
  const [selectedTreeNode, setSelectedTreeNode] = useState(null)
  const [expandedKeys, setExpandedKeys] = useState([])
  const [autoExpandParent, setAutoExpandParent] = useState(true)
  const [searchValue, setSearchValue] = useState('')
  const [isModalOpen, setIsModalOpen] = useState(false)
  const [modalType, setModalType] = useState('') // 'dept' or 'employee'
  const [form] = Form.useForm()
  const [columnarr, setColumnarr] = useState(initColumns)
  const [currentViewType, setCurrentViewType] = useState('dept') // 'dept' or 'employee'
  const [activeTabKey, setActiveTabKey] = useState('dept')
  const [deptData, setDeptData] = useState([])
  const [deptDataAll, setDeptDataAll] = useState([])
  const [positionData, setPositionData] = useState([])
  const [employeeData, setEmployeeData] = useState([])
  
  const { nowroute, setnowroute, collapsed, setcollapsed } = useStore();

  useEffect(() => {
    queryTreeData()
    queryTableData()
  }, [])

  // 查询树形数据
  const queryTreeData = async () => {
    setIsLoading(true)

    let rtdata = await fetchsync_util("/admin/zzjg/tree_manage_bm", 'POST', { }, "json")
    setDeptDataAll(rtdata.resultdata)
    setDeptData(rtdata.resultdata.filter(item => item.bmbm !== '0'))
    
    // 将扁平数组转换为树形结构
    const buildTree = (flatData) => {
      const treeMap = {};
      const tree = [];

      // 先创建所有节点的映射
      flatData.forEach(item => {
        treeMap[item.bmbm] = {
          title: item.bmmc,
          key: item.bmbm,
          id: item.id,
          children: []
        };
      });

      // 构建树形结构
      flatData.forEach(item => {
        const node = treeMap[item.bmbm];
        if (item.bmbm.includes('-')) {
          // 有父节点
          const parentKey = item.bmbm.substring(0, item.bmbm.lastIndexOf('-'));
          const parent = treeMap[parentKey];
          if (parent) {
            parent.children.push(node);
          }
        } else {
          // 根节点
          tree.push(node);
        }
      });

      // 移除空的children数组
      const removeEmptyChildren = (node) => {
        if (node.children.length === 0) {
          delete node.children;
        } else {
          node.children.forEach(child => removeEmptyChildren(child));
        }
      };
      tree.forEach(node => removeEmptyChildren(node));

      return tree;
    };

    const treeDataFromApi = buildTree(rtdata.resultdata);



    try {
      // 模拟数据，实际应该调用API
      const mockTreeData = [
        {
          title: '浙江盛世前程外包服务有限公司',
          key: '0',
          children: [
            {
              title: '总经理室',
              key: '0-0',
              children: []
            },
            {
              title: '管理中心',
              key: '0-1',
              children: [
                {
                  title: '管理团队',
                  key: '0-1-0',
                  children: []
                }
              ]
            }
          ]
        }
      ]
      //

      setTreeData(treeDataFromApi)
      setExpandedKeys(['0', '0-1'])
      
      // 默认选中bmbm=0的节点
      const defaultNode = rtdata.resultdata.find(item => item.bmbm === '0')
      if (defaultNode) {
        const defaultTreeNode = {
          key: defaultNode.bmbm,
          title: defaultNode.bmmc,
          id: defaultNode.id
        }
        setSelectedTreeNode(defaultTreeNode)
        // 触发选中事件，加载对应的表格数据
        queryTableData(defaultNode.bmbm, activeTabKey)
      }
    } catch (error) {
      openNotification_util('获取组织架构数据失败')
    }
    setIsLoading(false)
  }

  // 查询下级部门数据
  const queryDeptData = async (nodeKey = null) => {
    try {
      // 实际调用API获取下级部门数据
      const mockDeptData = [
        {
          key: '1',
          org_code: '800006',
          org_name: '管理团队',
          short_name: '管理团队',
          parent_name: '管理中心',
          org_level: '3',
          org_type: '部门',
          hierarchy: '3',
          manager: '张三',
          create_date: '2019-11-01',
          remark: ''
        },
        {
          key: '2',
          org_code: '800007',
          org_name: 'HRBP团队',
          short_name: 'HRBP团队',
          parent_name: '管理中心',
          org_level: '3',
          org_type: '部门',
          hierarchy: '3',
          manager: '李四',
          create_date: '2019-11-01',
          remark: ''
        }
      ]
      // setDeptData(dealnullorundenfined(mockDeptData))
    } catch (error) {
      openNotification_util('获取下级部门数据失败')
    }
  }

  // 查询下属岗位数据
  const queryPositionData = async (nodeKey = null) => {
    try {
      // 实际调用API获取岗位数据
      const mockPositionData = [
        {
          key: '1',
          position_code: 'g001',
          position_name: '董事',
          department: '营运中心',
          level: '高级',
          requirement: '本科及以上',
          responsibility: '负责企业战略决策',
          create_date: '2019-11-19',
          status: '启用'
        },
        {
          key: '2',
          position_code: 'GL0001',
          position_name: '总经理',
          department: '总经理室',
          level: '高级',
          requirement: '本科及以上',
          responsibility: '全面负责公司运营管理',
          create_date: '2020-11-06',
          status: '启用'
        },
        {
          key: '3',
          position_code: 'GL0002',
          position_name: '副总经理',
          department: '总经理室',
          level: '高级',
          requirement: '本科及以上',
          responsibility: '协助总经理管理公司',
          create_date: '2020-11-06',
          status: '启用'
        },
        {
          key: '4',
          position_code: 'GL0003',
          position_name: '中心总监',
          department: '管理中心',
          level: '中级',
          requirement: '本科及以上',
          responsibility: '负责治理监督工作',
          create_date: '2020-11-06',
          status: '启用'
        },
        {
          key: '5',
          position_code: 'GL0004',
          position_name: '中心总监',
          department: '财务中心',
          level: '中级',
          requirement: '本科及以上',
          responsibility: '负责财务监督工作',
          create_date: '2020-11-06',
          status: '启用'
        },
        {
          key: '6',
          position_code: 'GL0005',
          position_name: '中心总监',
          department: '营运中心',
          level: '中级',
          requirement: '本科及以上',
          responsibility: '负责营运监督工作',
          create_date: '2020-11-06',
          status: '启用'
        },
        {
          key: '7',
          position_code: 'GL0006',
          position_name: '部门经理',
          department: '管理团队',
          level: '中级',
          requirement: '本科及以上',
          responsibility: '负责部门日常管理',
          create_date: '2020-11-06',
          status: '启用'
        },
        {
          key: '8',
          position_code: 'GL0007',
          position_name: '部门主管',
          department: '管理团队',
          level: '中级',
          requirement: '本科及以上',
          responsibility: '负责部门业务管理',
          create_date: '2020-11-06',
          status: '启用'
        },
        {
          key: '9',
          position_code: 'GL0008',
          position_name: '专员',
          department: '管理团队',
          level: '初级',
          requirement: '大专及以上',
          responsibility: '负责具体业务执行',
          create_date: '2020-11-06',
          status: '启用'
        },
        {
          key: '10',
          position_code: 'GL0009',
          position_name: 'HRBP',
          department: 'HRBP团队',
          level: '中级',
          requirement: '本科及以上',
          responsibility: '负责人力资源业务伙伴',
          create_date: '2020-11-06',
          status: '启用'
        },
        {
          key: '11',
          position_code: 'GL0010',
          position_name: '部门经理',
          department: '财税管理团队',
          level: '中级',
          requirement: '本科及以上',
          responsibility: '负责财税管理工作',
          create_date: '2020-11-06',
          status: '启用'
        },
        {
          key: '12',
          position_code: 'GL0011',
          position_name: '部门主管',
          department: '财税管理团队',
          level: '中级',
          requirement: '本科及以上',
          responsibility: '负责财税业务管理',
          create_date: '2020-11-06',
          status: '启用'
        },
        {
          key: '13',
          position_code: 'GL0012',
          position_name: '会计',
          department: '财税管理团队',
          level: '初级',
          requirement: '大专及以上',
          responsibility: '负责会计核算工作',
          create_date: '2020-11-06',
          status: '启用'
        },
        {
          key: '14',
          position_code: 'GL0013',
          position_name: '出纳',
          department: '财税管理团队',
          level: '初级',
          requirement: '大专及以上',
          responsibility: '负责资金管理工作',
          create_date: '2020-11-06',
          status: '启用'
        },
        {
          key: '15',
          position_code: 'GL0014',
          position_name: '部门经理',
          department: '人事数据团队',
          level: '中级',
          requirement: '本科及以上',
          responsibility: '负责人事数据管理',
          create_date: '2020-11-06',
          status: '启用'
        },
        {
          key: '16',
          position_code: 'g001',
          position_name: '董事',
          department: '营运中心',
          level: '高级',
          requirement: '本科及以上',
          responsibility: '负责企业战略决策',                                                         
          create_date: '2019-11-19',
          status: '启用'
        },
        {
          key: '17',
          position_code: 'GL0001',
          position_name: '总经理',
          department: '总经理室',
          level: '高级',
          requirement: '本科及以上',
          responsibility: '全面负责公司运营管理',
          create_date: '2020-11-06',
          status: '启用'
        },
        {
            key: '18',
          position_code: 'GL0002',
          position_name: '副总经理',
          department: '总经理室',
          level: '高级',
          requirement: '本科及以上',
          responsibility: '协助总经理管理公司',
          create_date: '2020-11-06',
          status: '启用'
        },
        {
          key: '19',
          position_code: 'GL0003',
          position_name: '中心总监',
          department: '管理中心',
          level: '中级',
          requirement: '本科及以上',
          responsibility: '负责治理监督工作',
          create_date: '2020-11-06',
          status: '启用'
        },
        {
          key: '20',
          position_code: 'GL0004',
          position_name: '中心总监',
          department: '财务中心',
          level: '中级',
          requirement: '本科及以上',
          responsibility: '负责财务监督工作',
          create_date: '2020-11-06',
          status: '启用'
        },
        {
          key: '21',
          position_code: 'GL0005',
          position_name: '中心总监',
          department: '营运中心',
          level: '中级',
          requirement: '本科及以上',
          responsibility: '负责营运监督工作',
          create_date: '2020-11-06',
          status: '启用'
        },
        {
          key: '22',
          position_code: 'GL0006',
          position_name: '部门经理',
          department: '管理团队',
          level: '中级',
          requirement: '本科及以上',
          responsibility: '负责部门日常管理',
          create_date: '2020-11-06',
          status: '启用'
        },
        {
          key: '23',
          position_code: 'GL0007',
          position_name: '部门主管',
          department: '管理团队',
          level: '中级',
          requirement: '本科及以上',
          responsibility: '负责部门业务管理',
          create_date: '2020-11-06',
          status: '启用'
        },
        {
          key: '24',
          position_code: 'GL0008',
          position_name: '专员',
          department: '管理团队',
          level: '初级',
          requirement: '大专及以上',
          responsibility: '负责具体业务执行',
          create_date: '2020-11-06',
          status: '启用'
        },
        {
          key: '25',
          position_code: 'GL0009',
          position_name: 'HRBP',
          department: 'HRBP团队',
          level: '中级',
          requirement: '本科及以上',
          responsibility: '负责人力资源业务伙伴',
          create_date: '2020-11-06',
          status: '启用'
        },
        {
          key: '26',
          position_code: 'GL0010',
          position_name: '部门经理',
          department: '财税管理团队',
          level: '中级',
          requirement: '本科及以上',
          responsibility: '负责财税管理工作',
          create_date: '2020-11-06',
          status: '启用'
        },
        {
          key: '27',
          position_code: 'GL0011',
          position_name: '部门主管',
          department: '财税管理团队',
          level: '中级',
          requirement: '本科及以上',
          responsibility: '负责财税业务管理',
          create_date: '2020-11-06',
          status: '启用'
        },
        {
          key: '28',
          position_code: 'GL0012',
          position_name: '会计',
          department: '财税管理团队',
          level: '初级',
          requirement: '大专及以上',
          responsibility: '负责会计核算工作',
          create_date: '2020-11-06',
          status: '启用'
        },
        {
          key: '29',
          position_code: 'GL0013',
          position_name: '出纳',
          department: '财税管理团队',
          level: '初级',
          requirement: '大专及以上',
          responsibility: '负责资金管理工作',
          create_date: '2020-11-06',
          status: '启用'
        },
        {
          key: '30',
          position_code: 'GL0014',
          position_name: '部门经理',
          department: '人事数据团队',
          level: '中级',
          requirement: '本科及以上',
          responsibility: '负责人事数据管理',
          create_date: '2020-11-06',
          status: '启用'
        }
      ]
      setPositionData(dealnullorundenfined(mockPositionData))
    } catch (error) {
      openNotification_util('获取岗位数据失败')
    }
  }

  // 查询部门员工数据
  const queryEmployeeData = async (nodeKey = null) => {
    try {
      // 实际调用API获取员工数据
      const mockEmployeeData = [
        {
          key: '1',
          emp_code: '000001',
          emp_name: '孙洁',
          department: '总经理室',
          position: '总经理',
          phone: '13806819820',
          email: 'sunjie@company.com',
          hire_date: '1982-05-05',
          status: '在职'
        },
        {
          key: '2',
          emp_code: '000002',
          emp_name: '李春丹',
          department: '总经理室',
          position: '副总经理',
          phone: '13325021981',
          email: 'lichundan@company.com',
          hire_date: '1981-05-01',
          status: '在职'
        },
        {
          key: '3',
          emp_code: '000003',
          emp_name: '王琳',
          department: '营运二部本部人员',
          position: '专员',
          phone: '13310021981',
          email: 'wanglin@company.com',
          hire_date: '1981-10-21',
          status: '在职'
        },
        {
          key: '4',
          emp_code: '000004',
          emp_name: '张丽娜',
          department: '营运一部',
          position: '项目主管',
          phone: '13302119880',
          email: 'zhanglina@company.com',
          hire_date: '1988-05-03',
          status: '在职'
        },
        {
          key: '5',
          emp_code: '000005',
          emp_name: '俞宣林',
          department: '三明电力',
          position: '雇员',
          phone: '13302041991',
          email: 'yuxuanlin@company.com',
          hire_date: '1991-11-24',
          status: '在职'
        },
        {
          key: '6',
          emp_code: '000007',
          emp_name: '李雯',
          department: '人事数据团队',
          position: '专员',
          phone: '13309031983',
          email: 'liwen@company.com',
          hire_date: '1983-02-11',
          status: '在职'
        },
        {
          key: '7',
          emp_code: '000008',
          emp_name: '杨琦',
          department: '营运二部本部人员',
          position: '专员',
          phone: '13306211994',
          email: 'yangqi@company.com',
          hire_date: '1994-08-22',
          status: '在职'
        },
        {
          key: '8',
          emp_code: '000009',
          emp_name: '汪洋静宁',
          department: '财税管理团队',
          position: '财务副经理',
          phone: '13602031990',
          email: 'wangyangninggang@company.com',
          hire_date: '1990-05-12',
          status: '在职'
        },
        {
          key: '9',
          emp_code: '000010',
          emp_name: '汪春兰',
          department: '营运二部本部人员',
          position: '专员',
          phone: '13301241991',
          email: 'wangchunlan@company.com',
          hire_date: '1991-02-12',
          status: '在职'
        },
        {
          key: '10',
          emp_code: '000011',
          emp_name: '曹南洋',
          department: '营运六部',
          position: '校长',
          phone: '13302061994',
          email: 'caonanyang@company.com',
          hire_date: '1994-07-25',
          status: '在职'
        },
        {
          key: '11',
          emp_code: '000012',
          emp_name: '管瑞红',
          department: '营运二部本部人员',
          position: '专员',
          phone: '13325241977',
          email: 'guanruihong@company.com',
          hire_date: '1977-10-24',
          status: '在职'
        },
        {
          key: '12',
          emp_code: '000013',
          emp_name: '宋海军',
          department: '营运二部本部人员',
          position: '专员',
          phone: '14302811985',
          email: 'songhaijun@company.com',
          hire_date: '1985-06-16',
          status: '在职'
        },
        {
          key: '13',
          emp_code: '000014',
          emp_name: '黄磊',
          department: '营运二部本部人员',
          position: '专员',
          phone: '13308021986',
          email: 'huanglei@company.com',
          hire_date: '1986-03-14',
          status: '在职'
        },
        {
          key: '14',
          emp_code: '000015',
          emp_name: '应俊',
          department: '营运二部本部人员',
          position: '项目主管',
          phone: '13302051977',
          email: 'yingjun@company.com',
          hire_date: '1977-07-17',
          status: '在职'
        },
        {
          key: '15',
          emp_code: '000018',
          emp_name: '万晶',
          department: '营运二部本部人员',
          position: '专员',
          phone: '13307021981',
          email: 'wanjing@company.com',
          hire_date: '1981-07-09',
          status: '在职'
        }
      ]
      setEmployeeData(dealnullorundenfined(mockEmployeeData))
    } catch (error) {
      openNotification_util('获取员工数据失败')
    }
  }

  // 查询表格数据 - 根据当前tab类型查询对应数据
  const queryTableData = async (nodeKey = null, tabKey = activeTabKey) => {
    setIsLoading(true)
    try {
      switch(tabKey) {
        case 'dept':
          await queryDeptData(nodeKey)
          break
        case 'position':
          await queryPositionData(nodeKey)
          break
        case 'employee':
          await queryEmployeeData(nodeKey)
          break
        default:
          await queryDeptData(nodeKey)
      }
      setSelectedRowKeys([])
      setSelectedRows([])
    } catch (error) {
      openNotification_util('获取表格数据失败')
    }
    setIsLoading(false)
  }

  // 树节点选择
  const onTreeSelect = (selectedKeys, info) => {
    setSelectedTreeNode(info.node)

    // 切换到第一个tab
    setActiveTabKey('dept')

    console.log(deptData,"deptData============================")
    console.log(selectedKeys[0],"selectedKeys============================")
    
    // 过滤出选中部门的直接下级部门
    const filterDeptData = (deptDataAll || []).filter(dept => {
      // 如果选中的是根节点(0),则显示所有二级部门(0-x格式)
      if(selectedKeys[0] === '0') {
        const pattern = /^0-\d+$/;  // 匹配0-1, 0-2等格式
        return pattern.test(dept.bmbm);
      }
      
      // 如果选中的是二级节点(如0-1),则显示其下所有三级部门(0-1-x格式)
      const selectedPrefix = selectedKeys[0] + '-';
      const pattern = new RegExp(`^${selectedKeys[0]}-\\d+$`); // 匹配0-1-1, 0-1-2等格式
      return pattern.test(dept.bmbm);
    })

    console.log(filterDeptData,"filterDeptData============================")
    setDeptData(filterDeptData)
    queryTableData(selectedKeys[0], activeTabKey)
  }

  // 树节点展开
  const onTreeExpand = (expandedKeys) => {
    setExpandedKeys(expandedKeys)
    setAutoExpandParent(false)
  }

  // 搜索树节点
  const onTreeSearch = (value) => {
    setSearchValue(value)
    if (value) {
      const expandedKeys = getExpandedKeys(treeData, value)
      setExpandedKeys(expandedKeys)
      setAutoExpandParent(true)
    }
  }

  // 获取展开的节点keys
  const getExpandedKeys = (data, searchValue) => {
    const expandedKeys = []
    const loop = (data) => {
      data.forEach(item => {
        if (item.title.indexOf(searchValue) > -1) {
          expandedKeys.push(item.key)
        }
        if (item.children) {
          loop(item.children)
        }
      })
    }
    loop(data)
    return expandedKeys
  }

  // 高亮搜索文本
  const getTreeTitle = (title) => {
    if (searchValue && title.indexOf(searchValue) > -1) {
      const index = title.indexOf(searchValue)
      const beforeStr = title.substr(0, index)
      const afterStr = title.substr(index + searchValue.length)
      return (
        <span>
          {beforeStr}
          <span style={{ color: '#f50' }}>{searchValue}</span>
          {afterStr}
        </span>
      )
    }
    return title
  }

  // 递归处理树数据添加高亮
  const processTreeData = (data) => {
    return data.map(item => ({
      ...item,
      title: getTreeTitle(item.title),
      children: item.children ? processTreeData(item.children) : []
    }))
  }

  // 手动刷新
  const handleRefresh = () => {
    queryTreeData()
    queryTableData(selectedTreeNode?.key, activeTabKey)
  }

  // 新增部门
  const handleAddDept = () => {
    setModalType('dept')
    form.resetFields()
    setIsModalOpen(true)
  }

  // 新增员工
  const handleAddEmployee = () => {
    setModalType('employee')
    form.resetFields()
    setIsModalOpen(true)
  }

  // 编辑
  const handleEdit = () => {
    if (selectedRows.length !== 1) {
      openNotification_util("只可选择一条数据编辑!")
      return
    }
    setModalType(currentViewType)
    form.setFieldsValue(selectedRows[0])
    setIsModalOpen(true)
  }

  // 删除
  const handleDelete = async () => {
    if (selectedRows.length === 0) {
      openNotification_util("请选择要删除的数据!")
      return
    }
    try {
      // 实际调用删除API
      // let rtdata = await fetchsync_util("/admin/zzjg/delete", 'POST', { selectedRows }, "json")
      openNotification_util("删除成功")
      queryTableData()
    } catch (error) {
      openNotification_util('删除失败')
    }
  }

  // 导出
  const handleExport = () => {
    useexcelauto(selectedRows, columnarr, '组织架构')
  }

  // 模态框确认
  const handleModalOk = async () => {
   var rtdata = await fetchsync_util("/admin/zzjg/tree_manage_addbm", 'POST', { 
    bmmc: form.getFieldValue('org_name'),
    bmbm: form.getFieldValue('parentBmbm')
   }, "json")

   if(rtdata.rtstatus){
    openNotification_util("新增成功")
    setIsModalOpen(false)
    queryTreeData()
    queryTableData()
   }else{
    openNotification_util("新增失败")
   }
  }

  // Tab切换处理
  const handleTabChange = (key) => {
    setActiveTabKey(key)
    setCurrentViewType(key)
    queryTableData(selectedTreeNode?.key, key)
  }

  // 获取不同类型的表格列配置
  const getColumnsForTab = (tabKey) => {
    switch(tabKey) {
      case 'dept':
        return initColumns
      case 'position':
        return [
          { title: '岗位编码', dataIndex: 'position_code', key: 'position_code', width: 120, show: true },
          { title: '岗位名称', dataIndex: 'position_name', key: 'position_name', width: 200, show: true },
          { title: '所属部门', dataIndex: 'department', key: 'department', width: 150, show: true },
          { title: '岗位级别', dataIndex: 'level', key: 'level', width: 100, show: true },
          { title: '任职要求', dataIndex: 'requirement', key: 'requirement', width: 150, show: true },
          { title: '岗位职责', dataIndex: 'responsibility', key: 'responsibility', width: 200, show: true },
          { title: '创建日期', dataIndex: 'create_date', key: 'create_date', width: 120, show: true },
          { title: '状态', dataIndex: 'status', key: 'status', width: 80, show: true }
        ]
       
      case 'employee':
        return [
          { title: '员工编号', dataIndex: 'emp_code', key: 'emp_code', width: 120, show: true },
          { title: '员工姓名', dataIndex: 'emp_name', key: 'emp_name', width: 120, show: true },
          { title: '所属部门', dataIndex: 'department', key: 'department', width: 150, show: true },
          { title: '岗位', dataIndex: 'position', key: 'position', width: 120, show: true },
          { title: '联系方式', dataIndex: 'phone', key: 'phone', width: 120, show: true },
          { title: '邮箱', dataIndex: 'email', key: 'email', width: 200, show: true },
          { title: '入职日期', dataIndex: 'hire_date', key: 'hire_date', width: 120, show: true },
          { title: '状态', dataIndex: 'status', key: 'status', width: 80, show: true }
        ]
      default:
        return initColumns
    }
  }

  const styleobj = {
    linestyleflex: {
      display: "flex",
      flexDirection: "row",
      alignItems: "center",
      height: "3rem",
      paddingLeft: "1rem"
    }
  }

  const handleAddSubDept = (nodeData) => {
    console.log('添加子部门:', nodeData)
  // 获取父级部门编码
  const parentBmbm = nodeData.key;
  
  // 打开新增部门模态框
  setModalType('dept');
  setIsModalOpen(true);
  
  // 设置表单初始值
  form.setFieldsValue({
    parentBmbm: parentBmbm, // 保存父级部门编码用于后端定位
    org_type: '部门', // 默认类型为部门
    org_level: '3', // 默认级别
    create_date: getCurrentDate_util() // 设置当前日期
  });
  }
  const handleRename = (nodeData) => {
    console.log('修改名称:', nodeData)

    setModalType('dept')
    form.setFieldsValue({
      org_name: nodeData.title,
      parentBmbm: nodeData.key
    })
    setIsModalOpen(true)
  }

  return (
    <div style={{
      height: "94%", backgroundColor: `#F1F1F1`, right: "1%", top: "4vh", overflow: "hidden",
      backgroundSize: "100% 100%", width: collapsed ? "94%" : "84%", position: "absolute", color: "white", fontSize: "0.8rem"
    }}>
      <div style={styles.kshcontainer}>
        <Row gutter={16} style={{ height: '100%' }}>
          {/* 左侧树形区域 */}
          <Col span={6} style={{ height: '100%', borderRight: '1px solid #f0f0f0' }}>
            <Card 
              title={
                <div style={{ display: 'flex', alignItems: 'center' }}>
                  <ApartmentOutlined style={{ marginRight: 8 }} />
                  组织架构
                </div>
              }
              size="small" 
              style={{ height: '100%' }}
              bodyStyle={{ height: 'calc(100% - 57px)', overflow: 'auto', padding: '8px' }}
            >
              <Search
                style={{ marginBottom: 8 }}
                placeholder="搜索组织"
                onSearch={onTreeSearch}
                allowClear
              />
              {isLoading ? (
                <div style={{ textAlign: 'center', padding: '20px' }}>
                  <Spin />
                </div>
              ) : (
                <Tree
                  showLine
                  showIcon
                  expandedKeys={expandedKeys}
                  autoExpandParent={autoExpandParent} 
                  selectedKeys={selectedTreeNode ? [selectedTreeNode.key] : []}
                  onExpand={onTreeExpand}
                  onSelect={onTreeSelect}
                  treeData={processTreeData(treeData)}
                  titleRender={(nodeData) => {
                    const isSelected = selectedTreeNode?.key === nodeData.key;
                    return (
                      <div 
                        style={{ 
                          display: 'flex',
                          alignItems: 'center', 
                          width: '100%',
                          padding: '4px 8px',
                          borderRadius: '4px',
                          backgroundColor: isSelected ? '#e6f7ff' : 'transparent',
                          transition: 'all 0.3s'
                        }}
                        onMouseEnter={(e) => {
                          e.currentTarget.style.backgroundColor = '#f5f5f5';
                          const actionBtn = e.currentTarget.querySelector('.node-action-button');
                          if(actionBtn) actionBtn.style.visibility = 'visible';
                        }}
                        onMouseLeave={(e) => {
                          e.currentTarget.style.backgroundColor = isSelected ? '#e6f7ff' : 'transparent';
                          const actionBtn = e.currentTarget.querySelector('.node-action-button');
                          if(actionBtn) actionBtn.style.visibility = 'hidden';
                        }}
                      >
                        <span style={{ flex: 1 }}>{nodeData.title}</span>
                        <div className="node-action-button" style={{visibility: 'hidden'}}>
                          {/* <Button
                            type="text"
                            size="small"
                            icon={<PlusSquareOutlined />}
                            onClick={(e) => {
                              e.stopPropagation();
                              handleAddSubDept(nodeData);
                            }}
                          />
                          <Button 
                            type="text"
                            size="small"
                            icon={<EditOutlined />}
                            onClick={(e) => {
                              e.stopPropagation();
                              handleRename(nodeData);
                            }}
                          /> */}
                          <Dropdown
                            trigger={['click']}
                            menu={{
                              items: [
                                {
                                  key: '1',
                                  label: '添加子部门',
                                  icon: <PlusSquareOutlined />,
                                  onClick: () => handleAddSubDept(nodeData)
                                },
                                {
                                  key: '2',
                                  label: '修改名称', 
                                  icon: <EditOutlined />,
                                  onClick: () => handleRename(nodeData)
                                }
                              ]
                            }}
                          >
                            <Button
                              type="text" 
                              size="small"
                              icon={<EllipsisOutlined />}
                              onClick={e => e.stopPropagation()}
                            />
                          </Dropdown>
                        </div>
                      </div>
                    );
                  }}
                />
              )}
            </Card>
          </Col>

          {/* 右侧内容区域 */}
          <Col span={18} style={{ height: '100%' }}>
            <Card style={{ height: '100%' }} bodyStyle={{ height: '100%', padding: '8px' }}>
              <Tabs
                activeKey={activeTabKey}
                onChange={handleTabChange}
                tabBarStyle={{ marginBottom: '16px' }}
                tabBarExtraContent={{
                  right: (
                    <div style={{ display: 'flex', gap: '8px' }}>
                      <Button size="small" onClick={handleRefresh}>
                        <ReloadOutlined />刷新
                      </Button>
                      <Button size="small" onClick={handleExport}>
                        <FileExcelOutlined />导出
                      </Button>
                    </div>
                  )
                }}
              >
                <Tabs.TabPane
                  tab={
                    <span>
                      <ApartmentOutlined />
                      下级部门
                    </span>
                  }
                  key="dept"
                >
                  <div style={{ marginBottom: '16px' }}>
                    <Button style={{ backgroundColor: "white", color: "#15499A", fontWeight: "800", marginRight: 8 }}
                      onClick={handleAddDept}>
                      <PlusSquareOutlined />新增部门
                    </Button>
                    <Button style={{ backgroundColor: "white", color: "#15499A", fontWeight: "800", marginRight: 8 }}
                      onClick={handleEdit}>
                      <EditOutlined />编辑
                    </Button>
                    <Popconfirm title="确定删除吗?" onConfirm={handleDelete}>
                      <Button style={{ backgroundColor: "white", color: "#15499A", fontWeight: "800", marginRight: 8 }}>
                        <MinusSquareOutlined />删除
                      </Button>
                    </Popconfirm>
                  </div>
                  {isLoading ? (
                    <div style={{ textAlign: 'center', padding: '50px' }}>
                      <Spin />
                    </div>
                  ) : (
                    <Custom_table_hooks_config 
                      tabledata={activeTabKey === 'dept' ? deptData : []} 
                      tablecolnum={getColumnsForTab('dept')}
                      width="100%"
                      sfdoubleclick="false" 
                      ifhiddencchangeselecttype="true"
                      selectedRows={selectedRows} 
                      selectedRowKeys={selectedRowKeys}
                      defaultPageSize={20}
                      bordered
                      scroll={{ y: 'calc(100vh - 400px)', x: 1250 }}
                      handleselectson={(selectedRows, selectedRowKeys) => {
                        setSelectedRows(selectedRows)
                        setSelectedRowKeys(selectedRowKeys)
                      }}
                    />
                  )}
                </Tabs.TabPane>

                <Tabs.TabPane
                  tab={
                    <span>
                      <ProfileOutlined />
                      下属岗位
                    </span>
                  }
                  key="position"
                >
                  <div style={{ marginBottom: '16px' }}>
                    <Button style={{ backgroundColor: "white", color: "#15499A", fontWeight: "800", marginRight: 8 }}
                      onClick={() => {
                        setModalType('position')
                        form.resetFields()
                        setIsModalOpen(true)
                      }}>
                      <PlusSquareOutlined />新增岗位
                    </Button>
                    <Button style={{ backgroundColor: "white", color: "#15499A", fontWeight: "800", marginRight: 8 }}
                      onClick={handleEdit}>
                      <EditOutlined />编辑
                    </Button>
                    <Popconfirm title="确定删除吗?" onConfirm={handleDelete}>
                      <Button style={{ backgroundColor: "white", color: "#15499A", fontWeight: "800", marginRight: 8 }}>
                        <MinusSquareOutlined />删除
                      </Button>
                    </Popconfirm>
                  </div>
                  {isLoading ? (
                    <div style={{ textAlign: 'center', padding: '50px' }}>
                      <Spin />
                    </div>
                  ) : (
                    <Custom_table_hooks_config 
                      tabledata={activeTabKey === 'position' ? positionData : []} 
                      tablecolnum={getColumnsForTab('position')}
                      width="100%"
                      sfdoubleclick="false" 
                      ifhiddencchangeselecttype="true"
                      selectedRows={selectedRows} 
                      selectedRowKeys={selectedRowKeys}
                      defaultPageSize={20}
                      bordered
                      scroll={{ y: 'calc(100vh - 400px)', x: 1250 }}
                      handleselectson={(selectedRows, selectedRowKeys) => {
                        setSelectedRows(selectedRows)
                        setSelectedRowKeys(selectedRowKeys)
                      }}
                    />
                  )}
                </Tabs.TabPane>

                <Tabs.TabPane
                  tab={
                    <span>
                      <UserOutlined />
                      部门员工
                    </span>
                  }
                  key="employee"
                >
                  <div style={{ marginBottom: '16px' }}>
                    <Button style={{ backgroundColor: "white", color: "#15499A", fontWeight: "800", marginRight: 8 }}
                      onClick={handleAddEmployee}>
                      <UserOutlined />新增员工
                    </Button>
                    <Button style={{ backgroundColor: "white", color: "#15499A", fontWeight: "800", marginRight: 8 }}
                      onClick={handleEdit}>
                      <EditOutlined />编辑
                    </Button>
                    <Popconfirm title="确定删除吗?" onConfirm={handleDelete}>
                      <Button style={{ backgroundColor: "white", color: "#15499A", fontWeight: "800", marginRight: 8 }}>
                        <MinusSquareOutlined />删除
                      </Button>
                    </Popconfirm>
                  </div>
                  {isLoading ? (
                    <div style={{ textAlign: 'center', padding: '50px' }}>
                      <Spin />
                    </div>
                  ) : (
                    <Custom_table_hooks_config 
                      tabledata={activeTabKey === 'employee' ? employeeData : []} 
                      tablecolnum={getColumnsForTab('employee')}
                      width="100%"
                      sfdoubleclick="false" 
                      ifhiddencchangeselecttype="true"
                      selectedRows={selectedRows} 
                      selectedRowKeys={selectedRowKeys}
                      defaultPageSize={20}
                      bordered
                      scroll={{ y: 'calc(100vh - 400px)', x: 1250 }}
                      handleselectson={(selectedRows, selectedRowKeys) => {
                        setSelectedRows(selectedRows)
                        setSelectedRowKeys(selectedRowKeys)
                      }}
                    />
                  )}
                </Tabs.TabPane>
              </Tabs>
            </Card>
          </Col>
        </Row>

        {/* 新增/编辑模态框 */}
        <Modal
          title={
            modalType === 'dept' ? '新增部门' : 
            modalType === 'position' ? '新增岗位' : '新增员工'
          } 
          open={isModalOpen}
          onOk={handleModalOk}
          onCancel={() => setIsModalOpen(false)}
          width={600}
          styles={{
            header: {
              backgroundColor: '#E6F7FF'
            }
          }}
        >
          <Form form={form} layout="vertical">
            {modalType === 'dept' ? (
              <>
                <Form.Item
                  label="部门名称"
                  name="org_name"
                  rules={[{ required: true, message: '请输入部门名称' }]}
                >
                  <Input placeholder="请输入部门名称" />
                </Form.Item>
              </>
            ) : modalType === 'position' ? (
              <>
                <Form.Item
                  label="岗位编码"
                  name="position_code"
                  rules={[{ required: true, message: '请输入岗位编码' }]}
                >
                  <Input placeholder="请输入岗位编码" />
                </Form.Item>
                <Form.Item
                  label="岗位名称"
                  name="position_name"
                  rules={[{ required: true, message: '请输入岗位名称' }]}
                >
                  <Input placeholder="请输入岗位名称" />
                </Form.Item>
                <Form.Item label="所属部门" name="department">
                  <Select placeholder="请选择所属部门">
                    <Option value="管理团队">管理团队</Option>
                    <Option value="HRBP团队">HRBP团队</Option>
                  </Select>
                </Form.Item>
                <Form.Item label="岗位级别" name="level">
                  <Select placeholder="请选择岗位级别">
                    <Option value="初级">初级</Option>
                    <Option value="中级">中级</Option>
                    <Option value="高级">高级</Option>
                  </Select>
                </Form.Item>
                <Form.Item label="任职要求" name="requirement">
                  <Input.TextArea placeholder="请输入任职要求" />
                </Form.Item>
                <Form.Item label="岗位职责" name="responsibility">
                  <Input.TextArea placeholder="请输入岗位职责" />
                </Form.Item>
                <Form.Item label="状态" name="status">
                  <Select placeholder="请选择状态">
                    <Option value="启用">启用</Option>
                    <Option value="禁用">禁用</Option>
                  </Select>
                </Form.Item>
              </>
            ) : (
              <>
                <Form.Item
                  label="员工编号"
                  name="emp_code"
                  rules={[{ required: true, message: '请输入员工编号' }]}
                >
                  <Input placeholder="请输入员工编号" />
                </Form.Item>
                <Form.Item
                  label="员工姓名"
                  name="emp_name"
                  rules={[{ required: true, message: '请输入员工姓名' }]}
                >
                  <Input placeholder="请输入员工姓名" />
                </Form.Item>
                <Form.Item label="所属部门" name="department">
                  <Select placeholder="请选择所属部门">
                    <Option value="管理团队">管理团队</Option>
                    <Option value="HRBP团队">HRBP团队</Option>
                  </Select>
                </Form.Item>
                <Form.Item label="职位" name="position">
                  <Input placeholder="请输入职位" />
                </Form.Item>
                <Form.Item label="联系方式" name="phone">
                  <Input placeholder="请输入联系方式" />
                </Form.Item>
                <Form.Item label="邮箱" name="email">
                  <Input placeholder="请输入邮箱" />
                </Form.Item>
                <Form.Item label="状态" name="status">
                  <Select placeholder="请选择状态">
                    <Option value="在职">在职</Option>
                    <Option value="离职">离职</Option>
                  </Select>
                </Form.Item>
              </>
            )}
          </Form>
        </Modal>
      </div>
    </div>
  )
}

export default TreeManage

const styles = {
  kshcontainer: {
    width: "98%", 
    height: "95%", 
    position: "absolute", 
    top: "3%", 
    left: "1%", 
    backgroundColor: "white", 
    color: "black",
    borderRadius: "10px",
    padding: "16px"
  }
} 